package com.software.chemistry.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SecurityUtil {
    private static String asHexString(final byte[] data) {
        final StringBuilder sb = new StringBuilder();
        for (final byte b : data) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    private static byte[] md5(final byte[] data) {
        try {
            final MessageDigest msgDigest = MessageDigest.getInstance("MD5");
            msgDigest.update(data);
            return msgDigest.digest();
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对内容进行MD5，并且转化为大写后返回
     *
     * @param value
     * @return
     */
    public static String upperCaseMd5(final String value) {

        String md5data = md5String(value);
        if (!md5data.isEmpty()) {
            return md5data.toUpperCase();
        }
        return null;
    }

    public static String md5String(final String value) {
        if (!value.isEmpty()) {
            try {
                final byte[] data = value.getBytes("utf-8");
                if (null != data) {
                    final byte[] digest = md5(data);
                    if (null != digest) {
                        return asHexString(digest);
                    }
                }
            } catch (final UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
